﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Micrhard.FMCG.Server.Interface;
using Micrhard.FMCG.Server.Models;
using Micrhard.FMCG.Server.DataAccess;
using Micrhard.FMCG.Server.DTO;
using Microhard.Core;
using Microhard.Core.DBUtility;
using Micrhard.FMCG.Server.Msg;

namespace Micrhard.FMCG.Server.Impl
{
    public class OrderImpl : IOrder
    {
        public Microhard.Core.DBUtility.ExecutedResult Add(Models.OrderModel model)
        {
            throw new NotImplementedException();
        }

        public Microhard.Core.DBUtility.ExecutedResult Update(Models.OrderModel model)
        {
            throw new NotImplementedException();
        }

        public Microhard.Core.DBUtility.ExecutedResult Delete(List<Guid> ids)
        {
            throw new NotImplementedException();
        }

        public Microhard.Core.DBUtility.ExecutedResult Delete(Models.OrderModel model)
        {
            throw new NotImplementedException();
        }

        public Models.OrderModel GetModelByID(Guid id)
        {
            throw new NotImplementedException();
        }

        public Models.OrderModel GetModelByModel(Models.OrderModel model)
        {
            throw new NotImplementedException();
        }

        public List<Models.OrderModel> Query(Models.OrderModel Model, int pageIndex, int pageSize, out int totalCount)
        {
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            var emp = db.Employees.SingleOrDefault(e => e.UserName == this.scope.CurrentUserName);
            var ka = db.KAs.SingleOrDefault(k => k.KAID == Model.SelectKAIDForQuery);
            IEnumerable<Order> entities = null;
            totalCount = 0;
            if (ka != null)
            {
                entities = from b in db.Orders
                           where b.CompanyID == emp.CompanyID
                           && b.HQCompanyCode == ka.CustomerCode
                           select b;
                totalCount = entities.Count();
                var pagedEntities = entities.OrderByDescending(p => p.CreateTime).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                if (pagedEntities != null && pagedEntities.Count > 0)
                    return pagedEntities.Select(m => m.ToModel()).ToList();
            }
            return new List<OrderModel>();
        }

        public List<Models.OrderModel> Query(Models.OrderModel Model)
        {
            throw new NotImplementedException();
        }

        public Microhard.Core.DBUtility.ScopeResult scope
        {
            set;
            get;
        }

        //public List<Models.OrderModel> GetNew(Guid companyID, List<Models.OrderModel> orders)
        //{
        //    if (orders.Count == 0)
        //        return new List<OrderModel>();
        //    MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
        //    var ka = db.KAs.SingleOrDefault(k => k.CustomerCode == orders.First().HQCompanyCode && k.CompanyID == companyID);
        //    if (ka == null)
        //        return null;
        //    List<OrderModel> notExist;
        //    //获得不存在订单
        //    if (db.Orders.Count() == 0)
        //    {
        //        notExist = orders;
        //    }
        //    else
        //    {
        //        notExist = new List<OrderModel>();
        //        foreach (var n in orders)
        //        {
        //            //订单是否已经添加过
        //            int cnt = db.Orders.Count(x => x.Code == n.Code && x.CompanyID == companyID && x.FromKAID == ka.KAID);
        //            if (cnt == 0)
        //            {
        //                notExist.Add(n);
        //            }
        //        }
        //    }
        //    //插入到数据库中
        //    if (notExist.Count > 0)
        //    {
        //        notExist.ForEach(i =>
        //        {
        //            i.OrderID = Guid.NewGuid();
        //            var entity = i.ToEntity();
        //            entity.CreateTime = DateTime.Now;
        //            entity.Status = (int)OrderStatus.Save;
        //            entity.CompanyID = i.CompanyID;
        //            entity.DeliveryDate = null;
        //            entity.FromKAID = ka.KAID;
        //            db.AddToOrders(entity);
        //        });
        //        try
        //        {
        //            db.SaveChanges();
        //        }
        //        catch (Exception ex)
        //        {
        //            Log.Error("IOrderGetNew", ex);
        //        }
        //    }
        //    return notExist;
        //}


        public void UpdateReceiveGoods(Guid companyID, List<OrderModel> orders)
        {
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            var rcCodes = orders.Select(o => o.Code).ToList();
            var extOrders = (from o in db.Orders
                             where rcCodes.Contains(o.Code)
                             && o.CompanyID == companyID
                             select o).ToList();
            if (extOrders.Count > 0)
            {
                foreach (var o in extOrders)
                {
                    o.DeliveryDate = DateTime.Now;
                }
                try
                {
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    Log.Error("UpdateReceiveGoods", ex);
                }
            }
        }


        public ExecutedResult SaveDetail(Guid companyID, string orderCode, List<OrderDetailModelInServer> details, string kaCode)
        {
            //ExecutedResult result = new ExecutedResult();
            //MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            ////是否已经添加
            //var cnt = db.OrderDetails.Count(w => w.OrderCode == orderCode && w.Order.CompanyID == companyID &&
            //    w.ProductSaleMapping.KA.CustomerCode == kaCode);
            //if (cnt > 0)
            //    return result;
            //var order = db.Orders.SingleOrDefault(s => s.Code == orderCode && s.CompanyID == companyID);
            //var ka = db.KAs.SingleOrDefault(w => w.CompanyID == companyID && w.CustomerCode == kaCode);
            //if (order != null)
            //{
            //    details.ForEach(o =>
            //    {
            //        var entity = o.ToEntity();
            //        entity.OrderDetailID = Guid.NewGuid();
            //        entity.OrderID = order.OrderID;
            //        var prdmap = db.ProductSaleMappings.SingleOrDefault(s => s.CustomerCode == o.SKU && s.KA.CustomerCode == kaCode
            //            && s.KA.CompanyID == companyID);
            //        if (prdmap == null)
            //        {
            //            //在产品中添加
            //            var id = Guid.NewGuid();
            //            db.Products.AddObject(new Product
            //            {
            //                CompanyID = companyID,
            //                CreateTime = DateTime.Now,
            //                Mark = o.PrdName,
            //                ProductID = id,
            //                SN = id.ToString(),
            //            });
            //            //在在销产品中添加
            //            prdmap = new ProductSaleMapping
            //            {
            //                PrdDepID = Guid.NewGuid(),
            //                KAID = ka.KAID,
            //                ProductID = id,
            //                CustomerCode = o.SKU,
            //                CreateTime = DateTime.Now
            //            };
            //            db.ProductSaleMappings.AddObject(prdmap);
            //            db.SaveChanges();
            //        }
            //        entity.PrdMapSaledID = prdmap.PrdDepID;
            //        db.OrderDetails.AddObject(entity);
            //    });
            //    try
            //    {
            //        db.SaveChanges();
            //    }
            //    catch (Exception ex)
            //    {
            //        result.ErrorMsg.Add(DBOperationFailedStatus.AddFailed, OrderMsg.AddDetailFailed);
            //        Log.Error("OrderImpl.SaveDetail", ex);
            //    }
            //}
            //return result;
            throw new NotImplementedException();
        }
    }
}
